﻿
using System;
using System.Text;

namespace FacebookXmpp.Parse
{
    internal class XmlStream : IDisposable
    {
        private readonly StringParser _parser = new StringParser();
		private DocumentBuilder _sequence = new DocumentBuilder();
        private XmlParseState _state;
    	private Connection _connection;

        public StringBuilder Debug { get { return _connection.Debug; } }

        internal XmlStream(Connection connection)
            : this()
        {
            _connection = connection;
            
        }

		internal XmlStream( )
		{
            _state = new XmlStartElement(_sequence);
		}
       
        public void Add(string text)
        {
            if (string.IsNullOrEmpty(text))
                return;
			
        	_parser.Add( text );
        	_sequence.Initialize();

			while (!_parser.IsPaused)
				_state = _state.Parse( _parser );
        }

		public MessageData ConsumeNext(bool allowOpen)
		{
            Add(_connection.Recieve());

			if (allowOpen && Sequence.HasOpenElement)
				return Sequence.ConsumeOpenElement();
			
			if (Sequence.HasClosedElement)
				return Sequence.ConsumeClosedElement();
		
			if (allowOpen && Sequence.HasOpenElement)
				return Sequence.ConsumeOpenElement();

			if (Sequence.HasClosedElement)
				return Sequence.ConsumeClosedElement();

			return null;
		}

		internal DocumentBuilder Sequence { get { return _sequence;  } }

        public void Dispose()
        {
            if (_connection != null)
                _connection.Dispose();
        }

    	public void StartTls( )
    	{
    		_connection.StartTls();
    	}
    }
}
